# -*-coding: utf-8 -*-
"""
    @Theme   : Suzy Blog Utils
    @Time    : 2024/4/11 10:48
    @Author  : YamFish
    @Url     : https://www.zhihu.com/people/yamfish
"""
from flask import request, redirect, url_for
from urllib.parse import urlparse, urljoin


def is_safe_url(target):
    url = urlparse(urljoin(request.host_url, target))
    if url.scheme.lower() not in ('http', 'https'):
        return False
    if url.netloc != urlparse(request.host_url).netloc:
        return False
    return True


def redirect_back(default='blog.index', **kwargs):
    for target in request.args.get('next'), request.referrer:
        if not target:
            continue
        if is_safe_url(target):
            return redirect(target)
    return redirect(url_for(default, **kwargs))
